package com.gpframework.common.utils;

import cn.hutool.http.HttpRequest;
import com.gpframework.common.constant.WeiXinConstants;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.weixin.common.bean.Template;
import com.gpframework.common.weixin.common.util.AccessToken;
import com.gpframework.common.weixin.common.util.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 微信模版消息模版
 *
 * @author zcl
 */
@Component
public class TemplateMessageUtils {
    private static final Logger logger = LoggerFactory
            .getLogger(TemplateMessageUtils.class);
    /**
     * redis缓存
     */
    private static RedisCache redisCacheUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * 静态注入
     */
    @PostConstruct
    public void init() {
        TemplateMessageUtils.redisCacheUtil = this.redisCache;
    }

    /**
     * 测试发送模版消息(必须微信授权获取该消息才可发送)
     *
     * @param brandId
     * @param appId
     * @param appSecret
     * @return
     */
    public static String sendMsg(Long brandId, String appId, String appSecret) {
        //有格式时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String format = sdf.format(new Date());
        //模版消息内容
        String json = Template.New()
                .setTouser("oNOSJ4sXoc9s2g7J8LpILobkWZUY")
                .setTemplate_id("7qJPh12ee-gu4wo4hV7sqyCWUVSP8dLbYYgFvPpukr4")
                .setTopcolor("#743A3A")
                .setPage("pack-index/member/member")
                .add("thing1", "测试会员", "") //会员类型
                .add("date2", format, "") //开始时间
                .add("date3", format, "") //结束时间
                .build();
        //发送模版消息
        String resMsg = sendTemplateMessage(brandId, "member", appId, appSecret, json);
        logger.info("————————————————————消息模版返回：内容" + resMsg + "————————————————————");
        return resMsg;
    }

    /**
     * 发送模板消息
     *
     * @param brandId   品牌id
     * @param wxType    微信类型
     * @param appId     品牌的appId
     * @param appSecret 品牌的appSecret
     * @param jsonStr   发送的json
     * @return
     */
    public static String sendTemplateMessage(Long brandId, String wxType, String appId, String appSecret, String jsonStr) {
        //从缓存中获取token
        AccessToken accessToken = null;
        try {
            accessToken = WeixinUtil.getBrandAccessToken(brandId, wxType, appId, appSecret);
        } catch (Exception e) {
            logger.error("获取微信token失败：\n品牌id={},\n微信类型={},\nappId={},\nSecret={},\n返回数据={}", brandId, wxType, appId, appSecret, jsonStr);
        }
        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(accessToken.getAccess_token())) {
            logger.info("-----------accessToken为空-----------");
            return null;
        }
        return HttpRequest.post(WeiXinConstants.COMMON_SUBSCRIBE_SEND_URL + accessToken.getAccess_token())
                .body(jsonStr)
                .execute().body();
    }

    /**
     * 发送模板消息
     *
     * @param brandId   品牌id
     * @param wxType    微信类型
     * @param appId     品牌的appId
     * @param appSecret 品牌的appSecret
     * @param jsonStr   发送的json
     * @return
     */
    public static String sendAdvancedTemplateMessage(Long brandId, String wxType, String appId, String appSecret, String jsonStr) {
        //从缓存中获取token
        AccessToken accessToken = WeixinUtil.getBrandAccessToken(brandId, wxType, appId, appSecret);
        if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(accessToken.getAccess_token())) {
            throw new BaseException("-----------accessToken为空-----------");
        }
        return HttpRequest.post(WeiXinConstants.ADVANCED_SUBSCRIBE_SEND_URL + accessToken.getAccess_token())
                .body(jsonStr)
                .execute().body();
    }
}
